const curLink = "curLinkList";

export function setCurLink(value) {
  value = JSON.stringify(value);
  return window.sessionStorage.setItem(curLink, value);
}
export function getCurLink() {
  let value = window.sessionStorage.getItem(curLink);
  value = JSON.parse(value);
  return value;
}

export function openDB(
  dbName = "wallpaper",
  version = 1,
  storeName = "wallpaperstore",
  keyPath = "key",
  index = []
) {
  return new Promise((resolve, reject) => {
    //  兼容浏览器
    // eslint-disable-next-line @typescript-eslint/ban-ts-comment
    // @ts-ignore
    const { webkitIndexedDB, indexedDB, mozIndexedDB, msIndexedDB } = window;
    const indexDB = indexedDB || mozIndexedDB || webkitIndexedDB || msIndexedDB;

    let db = null;
    const request = indexDB.open(dbName, version);

    request.onsuccess = (e) => {
      db = e.target.result;
      resolve({
        code: 0,
        success: true,
        data: db,
        msg: "数据库打开成功!",
      });
    };

    request.onerror = (e) => {
      resolve({ code: -1, success: false, data: null, msg: "数据库打开失败!" });
    };

    request.onupgradeneeded = (e) => {
      db = e.target.result;

      const storeOptions = {
        autoIncrement: true,
      };

      if (keyPath && keyPath !== "") {
        storeOptions.autoIncrement = false;
        storeOptions.keyPath = keyPath;
      }

      // 创建表
      if (!db.objectStoreNames.contains(storeName)) {
        const store = db.createObjectStore(storeName, storeOptions);

        // 创建索引
        // indexName索引列名称
        // indexKey索引键值
        if (index && index.length > 0) {
          index.forEach((item) => {
            if (
              !item.indexName ||
              !item.indexKey ||
              item.options.unique === undefined
            ) {
              reject(
                "索引格式错误，请参照格式{indexName:'indexName',indexKey:'indexKey',{unique: false}}"
              );
            }

            store.createIndex(item.indexName, item.indexKey, item.options);
          });
        }
      }
    };
  });
}

/**
 * 新增数据
 * @param {object} db 数据库实例
 * @param {string} storeName 仓库名称
 * @param {object} dataConfig 添加的数据集合
 **/
export function addData(db, storeName, dataConfig) {
  return new Promise((resolve, reject) => {
    if (!db) {
      reject("数据库不存在或没有初始化");
    }
    if (!dataConfig || !dataConfig.value) {
      reject("value是必传项，参照格式{[keyPath]:'key',value:'value'}");
    }

    const req = db
      .transaction([storeName], "readwrite")
      .objectStore(storeName)
      .add(dataConfig);

    // 操作成功
    req.onsuccess = (e) => {
      resolve({ code: 0, success: true, data: null, msg: "数据写入成功!" });
    };

    // 操作失败
    req.onerror = () => {
      const data = {
        code: -1,
        success: false,
        data: null,
        msg: "数据写入失败!",
      };
      resolve(data);
    };
  });
}

/**
 * 更新数据
 * @param {object} db 数据库实例
 * @param {string} storeName 仓库名称
 * @param {object} dataConfig 更新的数据集合
 */
export function updateData(db, storeName, dataConfig) {
  return new Promise((resolve, reject) => {
    if (!db) {
      reject("数据库不存在或没有初始化");
    }

    if (!dataConfig || !dataConfig.value) {
      reject("value是必传项，参照格式{[keyPath]:'key',value:'value'}");
    }

    const req = db
      .transaction([storeName], "readwrite")
      .objectStore(storeName)
      .put(dataConfig);

    // 操作成功
    req.onsuccess = (e) => {
      resolve({ code: 0, success: true, data: null, msg: "数据更新成功!" });
    };

    // 操作失败
    req.onerror = () => {
      const data = {
        code: -1,
        success: false,
        data: null,
        msg: "数据更新失败!",
      };
      resolve(data);
    };
  });
}

/**
 * 查询数据
 * @param {object} db 数据库实例
 * @param {string} storeName 仓库名称
 * @param {string} key 数据主键
 **/
export function getData(db, storeName, key) {
  return new Promise((resolve, reject) => {
    if (!db) {
      reject("数据库不存在或没有初始化");
    }

    const req = db
      .transaction([storeName], "readonly")
      .objectStore(storeName)
      .get(key);

    // 操作成功
    req.onsuccess = (e) => {
      resolve({
        code: 0,
        success: true,
        data: e?.target?.result,
        msg: "数据获取成功!",
      });
    };
    // 操作失败
    req.onerror = () => {
      const data = {
        code: -1,
        success: false,
        data: null,
        msg: "数据获取失败!",
      };
      resolve(data);
    };
  });
}
